# -*- coding: utf-8 -*-
"""
Created on Wed Aug 22 10:28:29 2018

@author: Who

跨商财经
https://www.kuashangcj.com/news

"""

import requests
import re
import json
import time
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.get(url, timeout=30, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_tj(url):
    text = get_html_text(url)
    try:
        data = json.loads(text)['data']
        regex = re.compile(r'浏览  ·  ([\s\S]*?)</span>')
        dates = re.findall(regex, data)
        return dates
    except:
        return None


def count_process_one():
    d1 = 0
    d2 = 0
    d3 = 0

    h = time.strftime('%H', time.localtime(time.time()))

    url = 'https://www.kuashangcj.com/news?isAjax=true&type=recommend&loadcount=1'
    print('----跨商财经推荐最新获取第1页----')
    dates = get_dates_tj(url)
    if not dates:
        return (0, 0, 0)
    for date in dates:
        if '分钟前' in date:
            d1 += 1
        elif '小时前' in date and date[:-3] < h:
            d1 += 1
        elif '小时前' in date and date[:-3] >= h:
            d2 += 1
        else:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1

    return (d1, d2, d3)


def main():
    u = '跨商财经'
    t1 = count_process_one()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
